﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CQLQueries;
using CQLQueries.Analyzers;
using daSyntaxAnalyser.SyntaxTree;
using daBase;
using daDataLayer;
using System.IO;
using danalyser.Properties;
using danalyser.Controllers;

namespace danalyser.Interface.Forms
{
    public partial class CQLForm : Form
    {
        public CQLForm()
        {
            InitializeComponent();
        }

        public CQLForm(String fn)
        {
            InitializeComponent();
            SourceFiles.Items.Add(fn);
        }

        private void CQLForm_Load(object sender, EventArgs e)
        {
            CQL_LA.Instance.ErrorOccuredEvent += new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_SA.Instance.ErrorOccuredEvent += new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_Semantic.Instance.ErrorOccuredEvent += new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_Interpreter.Instance.ErrorOccuredEvent += new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_Interpreter.Instance.MsgEvent += new EventHandler<MsgArg>(GetMsg);
        }

        public void ErrorOccered(object sender, ErrorArgs e)
        {
            RezulData.Rows.Add();
            RezulData.Rows[RezulData.RowCount - 1].Cells[0].Value = Resources.Msg3;
            RezulData.Rows[RezulData.RowCount - 1].Cells[1].Value = e.Level + ": " + e.Message;
            //RezulData.Rows[RezulData.RowCount - 1].Cells[2].Value = e.Position;
            RezulData.Rows[RezulData.RowCount - 1].Cells[4].Value = 4;
            RezulData.Rows[RezulData.RowCount - 1].Cells[5].Value = e.BeginTok.ToString();
            RezulData.Rows[RezulData.RowCount - 1].Cells[6].Value = e.EndTok.ToString();
        }

        public void GetMsg(object sender, MsgArg e)
        {
            RezulData.Rows.Add();
            RezulData.Rows[RezulData.RowCount - 1].Cells[0].Value = Resources.Msg2;
            RezulData.Rows[RezulData.RowCount-1].Cells[1].Value = e.Msg;
            RezulData.Rows[RezulData.RowCount - 1].Cells[4].Value = 3;
            RezulData.Rows[RezulData.RowCount - 1].Cells[5].Value = e.Beg.ToString();
            RezulData.Rows[RezulData.RowCount - 1].Cells[6].Value = e.End.ToString();
            RezulData.Rows.Add();
            RezulData.Rows[RezulData.RowCount - 1].Cells[0].Value = Resources.Msg2;
            RezulData.Rows[RezulData.RowCount-1].Cells[1].Value = "Количество возвращённых ISyntaxElement = " + CQL_Interpreter.Instance.Rezult.Count;
            RezulData.Rows[RezulData.RowCount - 1].Cells[4].Value = 2;
            int i = 1;
            foreach(/*ISyntaxTreeElement*/Object elt in CQL_Interpreter.Instance.Rezult)
            {

                RezulData.Rows.Add();
                RezulData.Rows[RezulData.RowCount - 1].Cells[0].Value = Resources.Msg1;
                RezulData.Rows[RezulData.RowCount - 1].Cells[1].Value = elt.ToString();
                //RezulData.Rows[RezulData.RowCount - 1].Cells[2].Value = elt.StartInfo.Line.ToString();
                //RezulData.Rows[RezulData.RowCount - 1].Cells[3].Value = elt.StartInfo.File;
                RezulData.Rows[RezulData.RowCount - 1].Cells[4].Value = 1;
                i++;    
            }
            CQL_Interpreter.Instance.Rezult.Clear();
        }

        private void УдалитьПодстрокуИз_RichTextBox(RichTextBox box, String substr, bool b)
        {
            int count = 0;
            String[] Lines = box.Lines;
            String text = "";
            int SelectionStart = box.SelectionStart;
            for (int i = 0; i < Lines.Length; ++i)
            {
                if ((SelectionStart >= count) && (SelectionStart <= count + Lines[i].Length))
                {
                    int l = 0; 
                    if(Lines[i].Length<substr.Length) return;
                    if (!Lines[i].StartsWith(substr))
                    {
                        if (b)
                        {
                            while ((Lines[i][l]==substr[0]) && (l < Lines[i].Length)) l++;
                        }
                        else return;
                    }
                    else l = substr.Length;
                    String str = Lines[i].Substring(l);
                    text = text + str + '\n';
                    if (i != Lines.Length - 1)
                    {
                        for (int j = i + 1; j < Lines.Length; ++j)
                        {
                            text = text = text + Lines[j];
                            if (j < Lines.Length - 1)
                            {
                                text = text + '\n';
                            }
                        }
                    }
                    box.Text = text;
                    box.SelectionStart = SelectionStart - l;
                    return;
                }
                text = text + Lines[i] + '\n';
                count += Lines[i].Length;
            }
        }

        private void ДобавитьПодстрокуВ_RichTextBox(RichTextBox box, String substr)
        {
            int count = 0;
            String[] Lines = box.Lines;
            String text = "";
            int SelectionStart = box.SelectionStart;
            for (int i = 0; i < Lines.Length; ++i)
            {
                if ((SelectionStart >= count) && (SelectionStart <= count + Lines[i].Length))
                {
                    String str = substr + Lines[i];
                    text = text + str + '\n';
                    if (i != Lines.Length - 1)
                    {
                        for (int j = i + 1; j < Lines.Length; ++j)
                        {
                            text = text = text + Lines[j];
                            if (j < Lines.Length - 1)
                            {
                                text = text + '\n';
                            }
                        }
                    }
                    box.Text = text;
                    box.SelectionStart = SelectionStart + substr.Length;
                    return;
                }
                text = text + Lines[i] + '\n';
                count += Lines[i].Length;
            }
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = true;
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = false;
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                SourceFiles.Items.Add(openFileDialog1.FileName);
            }
        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            if (openFileDialog2.ShowDialog() == DialogResult.OK)
            {
                ТекстЗапроса.LoadFile(openFileDialog2.FileName, RichTextBoxStreamType.PlainText);
            }
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            SourceFiles.Items.RemoveAt(SourceFiles.SelectedIndex);
        }

        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = true;
            if (ТекстЗапроса.Text == "")
            {
                MessageBox.Show("Нет ни одного CQL-запроса!");
                return;
            }
            //РезультатЗапроса.Items.Clear();
            RezulData.Rows.Clear();
            String Query = ТекстЗапроса.Text;
            List<String> fn = new List<string>();
            if (SourceFiles.Items.Count == 0)
            {
                MessageBox.Show("Отсутствуют файлы для статического анализа!");
                return;
            }
            for (int i = 0; i < SourceFiles.Items.Count;++i )
            {
                fn.Add(SourceFiles.Items[i].ToString());
            }
            if (CQL_Interpreter.Instance.ExecuteQuery(Query, fn))
            {
                //РезультатЗапроса.Items.Add("Количество возвращённых ISyntaxElement = " + CQL_Interpreter.Instance.Rezult.Count);
                //int i = 1;
                //foreach (ISyntaxTreeElement elt in CQL_Interpreter.Instance.Rezult)
                //{
                //    РезультатЗапроса.Items.Add("[" + i.ToString() + "] " + elt.ToString());
                //    i++;
                //}
            }
        }

        private void toolStripButton5_Click_1(object sender, EventArgs e)
        {            
            ДобавитьПодстрокуВ_RichTextBox(ТекстЗапроса, "--");
        }

        private void toolStripButton6_Click_1(object sender, EventArgs e)
        {
            УдалитьПодстрокуИз_RichTextBox(ТекстЗапроса, "--", false);
        }

        private void toolStripButton3_Click_1(object sender, EventArgs e)
        {
            ДобавитьПодстрокуВ_RichTextBox(ТекстЗапроса, "      ");
        }

        private void toolStripButton4_Click_1(object sender, EventArgs e)
        {
            УдалитьПодстрокуИз_RichTextBox(ТекстЗапроса, "      ", true);
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ТекстЗапроса.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
            }
        }

        private void CQLForm_Shown(object sender, EventArgs e)
        {
            ТекстЗапроса.Focus();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {           
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (RezulData.RowCount == 0) return;
            int ind = RezulData.SelectedRows[0].Index;
            switch (Convert.ToInt32(RezulData.Rows[ind].Cells[4].Value))
            {
                case 1:
                    FormController.Instance.Editor.ShowLoad(Convert.ToString(RezulData.Rows[ind].Cells[3].Value),
                                                            Convert.ToInt32(RezulData.Rows[ind].Cells[2].Value), "test", false);
                    break;
                case 3:
                    
                    //break;
                case 4:
                    int beg = Convert.ToInt32(RezulData.Rows[ind].Cells[5].Value);
                    int end = Convert.ToInt32(RezulData.Rows[ind].Cells[6].Value);
                    if (beg == -1) return;
                    int len = end - beg;
                    if (len == 0) len = 1;
                    ТекстЗапроса.Select(beg-1, len);
                    break;
            }
        }

        private void dataGridView1_Paint(object sender, PaintEventArgs e)
        {
        }

        private void CQLForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            CQL_LA.Instance.ErrorOccuredEvent -= new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_SA.Instance.ErrorOccuredEvent -= new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_Semantic.Instance.ErrorOccuredEvent -= new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_Interpreter.Instance.ErrorOccuredEvent -= new EventHandler<ErrorArgs>(ErrorOccered);
            CQL_Interpreter.Instance.MsgEvent -= new EventHandler<MsgArg>(GetMsg);
        }
    }
}
